<?php


namespace app\erp\controller;


use app\erp\model\Orderdb;
use app\erp\model\Pikuandb;
use app\erp\model\PikuanLogdb;
use app\erp\model\PikuanRundb;
use app\erp\model\Pikuanxinxidb;
use think\Db;

class Pikuan extends Base
{
    protected $cols = array(
        /*array(
            'field' => 'pk_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),*/

        array(
            'field' => 'pk_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
        ),
        array(
            //'fixed' => 'right',
            'field' => 'oprate',
            'width' => 120,
            'toolbar' => '#pikuan_tool',
            'title' => '操作'
        ),
        array(
            //'fixed' => 'right',
            'field' => 'zhiyi_state',
            'width' => 60,
            'title' => '处理',
            'templet' => '#zhiyi_stateTpl'
        ),
        array(
            //'fixed' => 'right',
            'field' => 'state',
            'width' => 60,
            'title' => '认款',
            'templet' => '#stateTpl'
        ),
        array(
            'field' => 'is_mul',
            'width' => 80,
            'title' => '多编号',
            'templet' => '#is_mulTpl'
        ),
        array(
            'field' => 'return_code',
            'width' => 130,
            'title' => '回款编号'
        ),
        /*array(
            'field' => 'qiantai',
            'width' => 120,
            'title' => '前台状态'
        ),*/
        array(
            'field' => 'pay_time',
            'width' => 110,
            'title' => '回款时间'
        ),
        array(
            'field' => 'renkuanshijian',
            'width' => 110,
            'title' => '认款时间'
        ),
        array(
            'field' => 'intro',
            'width' => 160,
            'title' => '摘要'
        ),
        array(
            'field' => 'beizhu',
            'width' => 160,
            'title' => '备注'
        ),
        array(
            'field' => 'title',
            'width' => 300,
            'title' => '付款单位'
        ),
        array(
            'field' => 'money',
            'width' => 120,
            'title' => '金额'
        ),

        array(
            'field' => 'out_order_no',
            'width' => 200,
            'title' => '订单号'
        ),
        array(
            'field' => 'order_money',
            'width' => 120,
            'title' => '订单金额'
        ),
        array(
            'field' => 'jun_order_state',
            'width' => 100,
            'title' => '前台状态',
            'templet' => '#jun_order_stateTpl'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 160,
            'title' => '供应商'
        ),

        array(
            'field' => 'supplier_name_er',
            'width' => 160,
            'title' => '二级供应商'
        ),
        array(
            'field' => 'zhiyiren',
            'width' => 160,
            'title' => '质疑人'
        ),
        array(
            'field' => 'dianqiantai',
            'width' => 100,
            'title' => '点前台',
            'templet' => '#dianqiantaiTpl'
        ),
        array(
            'field' => 'zhiyi_order',
            'width' => 200,
            'title' => '质疑修改订单',
            'templet' => '#zhiyiTpl'
        ),
        array(
            'field' => 'reject_reason',
            'width' => 300,
            'title' => '驳回原因'
        ),
        array(
            'field' => 'admin_name',
            'width' => 120,
            'title' => '操作人'
        )

    );
    protected $cols_chakuan = array(
        array(
            'field' => 'pk_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
        ),
        array(
            //'fixed' => 'right',
            'field' => 'oprate',
            'width' => 80,
            'toolbar' => '#chakuan_tool',
            'title' => '操作'
        ),
        array(
            //'fixed' => 'right',
            'field' => 'zhiyi_state',
            'width' => 60,
            'title' => '处理',
            'templet' => '#zhiyi_stateTpl'
        ),
        array(
            //'fixed' => 'right',
            'field' => 'state',
            'width' => 60,
            'title' => '认款',
            'templet' => '#stateTpl'
        ),/*
        array(
            'field' => 'qiantai',
            'width' => 120,
            'title' => '前台状态'
        ),*/
        array(
            'field' => 'return_code',
            'width' => 130,
            'title' => '回款编号'
        ),
        array(
            'field' => 'pay_time',
            'width' => 110,
            'title' => '回款时间'
        ),
        array(
            'field' => 'renkuanshijian',
            'width' => 110,
            'title' => '认款时间'
        ),
        array(
            'field' => 'intro',
            'width' => 160,
            'title' => '摘要'
        ),
        array(
            'field' => 'beizhu',
            'width' => 160,
            'title' => '备注'
        ),
        array(
            'field' => 'title',
            'width' => 300,
            'title' => '付款单位'
        ),
        array(
            'field' => 'money',
            'width' => 120,
            'title' => '金额'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 200,
            'title' => '订单号'
        ),
        array(
            'field' => 'order_money',
            'width' => 120,
            'title' => '订单金额'
        ),
        array(
            'field' => 'jun_order_state',
            'width' => 100,
            'title' => '前台状态',
            'templet' => '#jun_order_stateTpl'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 160,
            'title' => '供应商'
        ),
        array(
            'field' => 'supplier_name_er',
            'width' => 160,
            'title' => '二级供应商'
        ),
        array(
            'field' => 'zhiyiren',
            'width' => 160,
            'title' => '质疑人'
        ),
        array(
            'field' => 'dianqiantai',
            'width' => 100,
            'title' => '点前台',
            'templet' => '#dianqiantaiTpl'
        ),
        array(
            'field' => 'zhiyi_order',
            'width' => 200,
            'title' => '质疑修改订单',
            'templet' => '#zhiyiTpl'
        ),
        array(
            'field' => 'reject_reason',
            'width' => 300,
            'title' => '驳回原因'
        ),
        array(
            'field' => 'admin_name',
            'width' => 120,
            'title' => '操作人'
        )
    );
    protected $cols_import = array(
        array(
            'field' => 'pk_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
        ),
        array(
            'width' => 140,
            'title' => '操作',
            'toolbar' => '#barPikuan'
        ),
        array(
            //'fixed' => 'right',
            'field' => 'state',
            'width' => 60,
            'title' => '状态',
            'templet' => '#stateTpl'
        ),
        array(
            'field' => 'return_code',
            'width' => 130,
            'title' => '回款编号',
        ),
        array(
            'field' => 'pay_time',
            'width' => 110,
            'title' => '回款时间',
        ),
        array(
            'field' => 'title',
            'width' => 300,
            'title' => '付款单位',
        ),
        array(
            'field' => 'money',
            'width' => 100,
            'title' => '金额',
        ),
        array(
            'field' => 'intro',
            'width' => 200,
            'title' => '摘要'
        ),
        /*array(
            'field' => 'order_level',
            'width' => 100,
            'title' => '运算单量'
        ),
        array(
            'field' => 'times_text',
            'width' => 100,
            'title' => '运算方式'
        ),
        array(
            'field' => 'runs',
            'width' => 100,
            'title' => '运算状态',
            'templet' => '#runTpl'
        ),*//*
        array(
            'field' => 'pkxx',
            'width' => 300,
            'title' => '运算数据',
            'templet' => '#pkxxTpl'
        ),*/
        /*
        array(
            'field' => 'state',
            'width' => 100,
            'title' => '操作状态',
            'templet' => '#stateTpl'
        ),*/
        array(
            'field' => 'default_order_no',
            'width' => 200,
            'title' => '指定订单',
        ),
        array(
            'field' => 'default_group',
            'width' => 200,
            'title' => '匹配订单',
        ),
        array(
            'field' => 'runs',
            'width' => 100,
            'title' => '匹配数量',
        ),
        array(
            'field' => 'admin_name',
            'width' => 120,
            'title' => '操作人'
        ),
    );
    public $post = array();

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
    }

    public function index()
    {
        $this->assign('admin_arr', array('193' => 'jun_admin', '263' => '李佳桐', '445' => '郭雅慧', '485' => '陈丽'));
        $this->assign('cols', json_encode($this->cols));
        return $this->fetch();
    }

    public function chakuan()
    {
        $this->assign('cols', json_encode($this->cols_chakuan));
        return $this->fetch();
    }

    public function importpklist()
    {
        $pikuanModel = new Pikuandb();
        /*if (!isset($this->post['order_type'])) {
            $this->post['order_type'] = -1;
        }*/
        $pikuanModel->param = $this->post;
        $get_list = $pikuanModel
            //->where('state', -1)
            ->order($this->post['_o'], $this->post['_b'])
            ->paginate($this->post['limit']);
        $get_list->append(['order']);
        $data = [];
        foreach ($get_list->items() as $key => $val) {
            $val['money'] = number_format($val['money'], 2, '.', '');
            /*foreach ($val['order'] as $keys => $vals) {
                $temp = array(
                    'out_order_no' => $vals['out_order_no'],
                    'order_money' => number_format($vals['order_money'] / 100, 2, '.', '')
                );
                array_push($data, array_merge($val->toArray(), $temp));
            }*/
            array_push($data, $val->toArray());
        }
        $this->layuiReturn($data, $get_list->total());
    }

    public function ajaxList()
    {
        $pikuanModel = new Pikuandb();
        $pikuanModel->param = $this->post;
        $get_list = $pikuanModel
            //->where('state', '>', -1)
            ->order($this->post['_o'], $this->post['_b'])
            ->paginate($this->post['limit']);
        //halt($pikuanModel->getLastSql());
        $get_list->append(['order']);
        $data = [];
        foreach ($get_list->items() as $key => $val) {
            $val['money'] = number_format($val['money'], 2, '.', '');
            foreach ($val['order'] as $keys => $vals) {
                $temp = array(
                    'out_order_no' => $vals['out_order_no'],
                    'order_money' => number_format($vals['order_money'] / 100, 2, '.', ''),
                    'supplier_name' => $vals['supplier_name'],
                    'supplier_name_er'=>$vals['supplier_name_er'],
                    'jun_order_state' => $vals['jun_order_state']
                );
                array_push($data, array_merge($val->toArray(), $temp));
            }
        }
        $this->layuiReturn($data, $get_list->total());
    }

    // 导出认款查询
    public function exportrk()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');
        $pikuanModel = new Pikuandb();
        $pikuanModel->param = $this->post;
        $get_list = $pikuanModel
            //->where('state', '>', -1)
            ->order($this->post['_o'], $this->post['_b'])
            ->select();
        $get_list->append(['order']);
        $data = [];
        if ($get_list) {
            foreach ($get_list as $key => $val) {
                $val['money'] = number_format($val['money'], 2, '.', '');
                foreach ($val['order'] as $keys => $vals) {
                    $temp = array(
                        'out_order_no' => $vals['out_order_no'],
                        'order_money' => number_format($vals['order_money'] / 100, 2, '.', ''),
                        'supplier_name' => $vals['supplier_name'],
                        'jun_order_state' => $vals['jun_order_state']
                    );
                    array_push($data, array_merge($val->toArray(), $temp));
                }
            }

            vendor("PHPExcel.PHPExcel");
            $phpExcel = new \PHPExcel ();
            ob_end_clean();
            $excel_name = '认款' . date('Ymdhi') . rand(1000, 9999) . '.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $header_data = array(
                '回款编号',
                '回款时间',
                '认款日期',
                '回款单位',
                '摘要',
                '订单已回款',
                '回款订单',
                '订单金额',
                '供应商',
                '前台状态',
                '质疑人',
                '质疑订单号',
                '驳回原因'
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);

            $jun_order_state_arr = ['无效订单', '待确认', '待发货', '待支付', '待收货', '已完成', '已退货', '已取消', '待妥投', '已废止', '未同步'];

            $excel_data = array();
            foreach ($data as $key => $val) {
                $temp [0] = $val ['return_code'];
                $temp [1] = $val ['pay_time'];
                $temp [2] = $val ['renkuanshijian'];
                $temp [3] = $val['title'];
                $temp [4] = $val['intro'];
                $temp [5] = $val['money'];
                $temp [6] = $val['out_order_no'];
                $temp [7] = $val['order_money'];
                $temp [8] = $val['supplier_name'];
                $temp [9] = $jun_order_state_arr[$val['jun_order_state']];
                $temp [10] = $val['zhiyiren'];
                $temp [11] = $val['zhiyi_order'];
                $temp [12] = $val['reject_reason'];
                array_push($excel_data, $temp);
            }
            $vAlign = new \PHPExcel_Style_Alignment ();
            $this->setExcelBodyMerge($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

            $obj_write->save('./uploads/Excel/' . $excel_name);
            $all_path = $excel_name;
            $this->layuiReturn(url('Order/downExcel', array(
                'excel_name' => $all_path
            )), 1, '导出成功', 1);

        }
    }

    public function importpk()
    {
        $this->assign('cols', json_encode($this->cols_import));
        return $this->fetch();
    }

    // 导出匹款查询结果
    public function exportpk()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');
        $pikuandb = new Pikuandb();
        $pikuandb->param = $this->post;
        $data = $pikuandb
            //->where('state', '-1')
            ->order('pk_id', 'asc')->select();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '匹款' . date('Ymdhi') . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '回款编号',
            '回款时间',
            '付款单位',
            '金额',
            '摘要',
            '指定订单',
            '匹配订单',
            '操作人'
        );

        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        foreach ($data as $key => $val) {
            $temp [0] = $val ['return_code'];
            $temp [1] = $val ['pay_time'];
            $temp [2] = $val['title'];
            $temp [3] = $val['money'];
            $temp [4] = (string)$val['intro'];
            $temp [5] = implode(',',$val['default_order_no']);
            $temp [6] = $val['order_nos'];
            $temp [7] = $val['admin_name'];
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    // 合并单元格
    protected function setExcelBodyMerge($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        $merge_length = 6; // 合并长度
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < $merge_length; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < $merge_length; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 不用合并单元格
    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    // 上传已匹款
    public function yipikuan()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        Db::startTrans();
        try {
            $orderdb = new Orderdb();
            foreach ($files as $file) {
                $info = $file->validate([
                    'site' => 1024 * 10 * 1024 * 1024,
                    'ext' => 'xls,xlsx'
                ])->move('./uploads/');
                if ($info) {
                    $fileName = './uploads/' . $info->getSaveName();
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objReader->setReadDataOnly(true);
                    $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                    $sheet = $objPHPExcel->getSheet();
                    $get_row_num = $sheet->getHighestRow(); // 总行数
                    $data = array();
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    $return_code_arr = [];
                    for ($i = 2; $i <= $get_row_num; $i++) {
                        $temp ['return_code'] = $this->getSheetValue($the_sheet, "A" . $i);
                        // 字段的格式，如果时间格式用下面的 如果是字符串格式用strtotime
                        $temp ['pay_time'] = date('Y-m-d H:i:s', intval(($this->getSheetValue($the_sheet, "B" . $i) - 25569) * 3600 * 24 - 28800));
                        $temp ['title'] = $this->getSheetValue($the_sheet, "C" . $i);
                        $temp ['intro'] = $this->getSheetValue($the_sheet, "E" . $i);
                        $temp ['money'] = $this->getSheetValue($the_sheet, "D" . $i);
                        $order_no_arr = explode("\n", $this->getSheetValue($the_sheet, "F" . $i));
                        /*$new_arr = array_filter($order_no_arr, function ($value) {
                            if (!empty($value)) {
                                return $value;
                            }
                        });*/
                        $new_arr = [];
                        foreach ($order_no_arr as $key => $val) {
                            if (!empty($val)) {
                                $t1 = explode('-', $val);
                                array_push($new_arr, $t1[0]);
                            }
                        }
                        $temp ['default_order_no'] = $new_arr;
                        $temp ['order_nos'] = implode(',', $new_arr);
                        $temp ['state'] = count($new_arr) > 0 ? 1 : 0;
                        $temp ['overflow'] = false;
                        $temp ['times'] = 1;
                        $temp ['runs'] = -1;
                        $temp['order_level'] = 1;
                        $temp['admin_id'] = MEMBER_ID;
                        //$temp['renkuanshijian'] = $this->getSheetValue($the_sheet, "G" . $i) ? date('Y-m-d H:i:s', intval(($this->getSheetValue($the_sheet, "G" . $i) - 25569) * 3600 * 24 - 28800)) : '';
                        $temp['renkuanshijian'] = $this->getSheetValue($the_sheet, "G" . $i) ? date('Y-m-d', intval(($this->getSheetValue($the_sheet, "G" . $i) - 25569) * 3600 * 24 - 28800)) : date('Y-m-d');
                        $temp['beizhu'] = $this->getSheetValue($the_sheet, "H" . $i);
                        if (count($new_arr) > 0) {
                            foreach ($new_arr as $out_order_no) {
                                // 直接更新
                                $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
                                if ($get_order) {
                                    //$get_order->save(['pay_state' => 2, 'pay_time' => strtotime($temp ['pay_time'])]);
                                }
                            }
                        }
                        array_push($return_code_arr, $temp['return_code']);
                        array_push($data, $temp);
                    }
                    if (count($data) > 0) {
                        $pikuandb = new Pikuandb();
                        if (count($return_code_arr)) {
                            $update_data = $pikuandb->whereIn('return_code', $return_code_arr)->select();
                            if (!$update_data->isEmpty()) {
                                foreach ($update_data as $key => $val) {
                                    $val->save(['is_delete' => 1]);
                                }
                            }
                        }
                        $pikuandb->saveAll($data);
                        Db::commit();
                        $this->layuiReturn($data, 0, '导入成功', 1);
                    } else {
                        Db::rollback();
                        $this->layuiReturn('导入失败', 0, '没有数据', 0);
                    }
                } else {
                    Db::rollback();
                    $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
                }
            }

        } catch (\Exception $e) {
            Db::rollback();
            $this->layuiReturn('excel格式错误' . $e->getMessage(), 0, 'excel格式错误', 0);
        }
    }

    // 导入前台状态
    public function qiantai()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        Db::startTrans();
        try {
            $pikuandb = new Pikuandb();
            foreach ($files as $file) {
                $info = $file->validate([
                    'site' => 1024 * 10 * 1024 * 1024,
                    'ext' => 'xls,xlsx'
                ])->move('./uploads/');
                if ($info) {
                    $fileName = './uploads/' . $info->getSaveName();
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objReader->setReadDataOnly(true);
                    $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                    $sheet = $objPHPExcel->getSheet();
                    $get_row_num = $sheet->getHighestRow(); // 总行数
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    for ($i = 2; $i <= $get_row_num; $i++) {
                        $return_code = $this->getSheetValue($the_sheet, "A" . $i);
                        // 状态
                        $qiantai = $this->getSheetValue($the_sheet, "B" . $i);
                        $get_pikuan = $pikuandb->where('return_code', $return_code)->find();
                        if ($get_pikuan) {
                            $get_pikuan->save(['qiantai' => $qiantai]);
                        }
                    }
                    Db::commit();
                    $this->layuiReturn('导入成功', 0, '导入成功', 1);
                } else {
                    Db::rollback();
                    $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
                }
            }

        } catch (\Exception $e) {
            Db::rollback();
            $this->layuiReturn('excel格式错误' . $e->getMessage(), 0, 'excel格式错误', 0);
        }
    }

    // 上传匹款单
    public function uploadPkd()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        try {
            foreach ($files as $file) {
                $info = $file->validate([
                    'site' => 1024 * 10 * 1024 * 1024,
                    'ext' => 'xls,xlsx'
                ])->move('./uploads/');
                if ($info) {
                    $fileName = './uploads/' . $info->getSaveName();
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objReader->setReadDataOnly(true);
                    $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                    $sheet = $objPHPExcel->getSheet();
                    $get_row_num = $sheet->getHighestRow(); // 总行数
                    $data = array();
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    $return_code_arr = array();
                    $run_data = array();
                    for ($i = 2; $i <= $get_row_num; $i++) {
                        $temp ['return_code'] = $this->getSheetValue($the_sheet, "A" . $i);
                        // 字段的格式，如果时间格式用下面的 如果是字符串格式用strtotime
                        $temp ['pay_time'] = date('Y-m-d H:i:s', intval(($this->getSheetValue($the_sheet, "B" . $i) - 25569) * 3600 * 24 - 28800));

                        /*print_r($temp ['pay_time']);
                        halt('111');
                        exit();*/
                        //$temp ['pay_time'] = str_replace('/','-',$this->getSheetValue($the_sheet, "B" . $i));
                        $temp ['title'] = $this->getSheetValue($the_sheet, "C" . $i);
                        $temp ['intro'] = $this->getSheetValue($the_sheet, "E" . $i);
                        $temp ['money'] = floatval($this->getSheetValue($the_sheet, "D" . $i));
                        /*$order_no_arr = explode(',', $this->getSheetValue($the_sheet, "F" . $i));
                        $new_arr = array_filter($order_no_arr, function ($value) {
                            if (!empty($value)) {
                                return $value;
                            }
                        });*/

                        $order_no_arr = explode("\n", $this->getSheetValue($the_sheet, "F" . $i));
                        /*$new_arr = array_filter($order_no_arr, function ($value) {
                            if (!empty($value)) {
                                return $value;
                            }
                        });*/
                        $new_arr = [];
                        foreach ($order_no_arr as $key => $val) {
                            if (!empty($val)) {
                                $t1 = explode('-', $val);
                                array_push($new_arr, $t1[0]);
                            }
                        }

                        $temp ['default_order_no'] = $new_arr;
                        $temp ['state'] = -2;
                        $temp ['overflow'] = false;
                        $temp ['times'] = 1;
                        $temp['order_level'] = 1;
                        $temp['admin_id'] = MEMBER_ID;
                        $temp_run = [];
                        $temp_run['return_code'] = $temp ['return_code'];
                        $temp_run['title'] = $temp ['title'];
                        $temp_run['money'] = $temp ['money'];
                        $temp_run['start_date'] = date('Y-m-d', strtotime('-6 month'));
                        $temp_run['end_date'] = date('Y-m-d');
                        $temp_run['admin_id'] = MEMBER_ID;
                        array_push($run_data, $temp_run);
                        array_push($data, $temp);
                        array_push($return_code_arr, $temp['return_code']);
                    }

                    if (count($data) > 0) {
                        $pikuandb = new Pikuandb();
                        if (count($return_code_arr)) {
                            $update_data = $pikuandb->whereIn('return_code', $return_code_arr)->select();
                            if (!$update_data->isEmpty()) {
                                foreach ($update_data as $key => $val) {
                                    $val->save(['is_delete' => 1]);
                                }
                            }
                        }

                        /*$data = $this->onePikuan($data, 1);
                        $pikuandb = new Pikuandb();
                        $data = array_filter($data, function ($value) {
                            return $value['open'] == 0;
                        });*/

                        // 保存运行记录
                        $pikuanLoddb = new PikuanLogdb();
                        $pikuanLoddb->saveAll($run_data);

                        // 日志
                        $log_data = [];
                        foreach ($data as $key => $val) {
                            $temp = [];
                            $temp['return_code'] = $val['return_code'];
                            $temp['log_txt'] = '导入匹款单';
                            $temp['param'] = json_encode(array('pay_time' => $val['pay_time'], 'title' => $val['title'], 'intro' => $val['intro'], 'money' => $val['money']));
                            $temp['result'] = '导入成功';
                            $temp['log_date'] = date('Y-m-d H:i:s');
                            array_push($log_data, $temp);
                        }
                        $pikuanLoddb = new PikuanLogdb();
                        $pikuanLoddb->saveAll($log_data);
                        // 日志结束
                        $pikuandb->saveAll($data);
                        $this->layuiReturn($data, 0, '导入成功', 1);
                    } else {
                        $this->layuiReturn('导入失败', 0, '没有数据', 0);
                    }
                } else {
                    $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
                }
            }
        } catch (\Exception $e) {
            $this->layuiReturn('excel格式错误' . $e->getMessage(), 0, 'excel格式错误', 0);
        }

    }

    // 上传回款单位
    public function uploadXx()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        try {
            foreach ($files as $file) {
                $info = $file->validate([
                    'site' => 1024 * 10 * 1024 * 1024,
                    'ext' => 'xls,xlsx'
                ])->move('./uploads/');
                if ($info) {
                    $fileName = './uploads/' . $info->getSaveName();
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objReader->setReadDataOnly(true);
                    $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                    $sheet = $objPHPExcel->getSheet();
                    $get_row_num = $sheet->getHighestRow(); // 总行数
                    $data = array();
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    for ($i = 2; $i <= $get_row_num; $i++) {
                        $temp ['fkdw'] = $this->getSheetValue($the_sheet, "A" . $i);
                        $temp ['address'] = $this->getSheetValue($the_sheet, "B" . $i);
                        $temp ['phone'] = $this->getSheetValue($the_sheet, "C" . $i);
                        $temp ['xxp'] = $this->getSheetValue($the_sheet, "D" . $i);
                        array_push($data, $temp);
                    }
                    if (count($data) > 0) {
                        $pikuanxinxidb = new Pikuanxinxidb();
                        $pikuanxinxidb->saveAll($data);
                        $this->layuiReturn($data, 0, '导入成功', 1);
                    } else {
                        $this->layuiReturn('导入失败', 0, '没有数据', 0);
                    }
                } else {
                    $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
                }
            }
        } catch (\Exception $e) {
            $this->layuiReturn('excel格式错误' . $e->getMessage(), 0, 'excel格式错误', 0);
        }

    }

    // 第一次匹款
    protected function onePikuan($data, $times)
    {
        $this->initPikuan($data, $times);
        foreach ($data as $key => $val) {
            $data[$key]['order_no_group'] = array();
            if ($data[$key]['open'] == 0) {
                if (count($val['default_order_no']) == 0) {
                    /*$get_order_nos = Db::name('order')->alias('o')->where('o.huikuandanwei', $val['title'])
                        ->where('o.order_money', $val['money'] * 100)
                        ->where('pay_state', 1)
                        ->column('o.out_order_no');
                     if (count($get_order_nos)) {
                        array_push($data[$key]['order_no_group'], $get_order_nos);
                    }
                   */
                    $get_order_nos = Db::name('order')->alias('o')->where('o.huikuandanwei', $val['title'])
                        ->where('o.order_money', $val['money'] * 100)
                        ->whereNotIn('o.order_type', [5, 7])
                        ->where('pay_state', 1)
                        ->value('o.out_order_no');
                    if ($get_order_nos) {
                        array_push($data[$key]['order_no_group'], $get_order_nos);
                    }
                } else {
                    array_push($data[$key]['order_no_group'], $val['default_order_no']);
                }
            }
        }
        $this->initDefualt($data);
        return $data;
    }

    // 初始化匹款状态
    protected function initPikuan(&$data, $times = 1)
    {
        $pikuandb = new Pikuandb();
        foreach ($data as $key => $val) {
            $data[$key]['times'] = $times;
            $data[$key]['open'] = $pikuandb->where('return_code', $val['return_code'])->count();
        }
    }

    // 初始化默认选项
    protected function initDefualt(&$data)
    {
        foreach ($data as $key => $val) {
            if (count($val['order_no_group']) == 1) {
                $data[$key]['default_group'] = $val['order_no_group'][0];
                $data[$key]['runs'] = 1;
            } elseif (count($val['order_no_group']) == 0) {
                $data[$key]['runs'] = 0;
            } else {
                $data[$key]['runs'] = 2;
            }
        }
    }

    // 匹款按钮
    public function titlePikuan()
    {
        $pikuandb = new Pikuandb();
        $pikuandb->param = $this->post['where_json'];
        $where = $pikuandb
            ->field('return_code,title,money,pk_id')
            ->where('is_mul', 0)
            ->where('state', '<', 1)
            ->select();
        $save_data = [];
        $start_date = $this->post['start_time'];
        $end_date = $this->post['end_time'];
        $pikuan_data = [];
        foreach ($where as $key => $val) {
            $temp = [];
            $temp['return_code'] = $val['return_code'];
            $temp['money'] = $val['money'];
            $temp['title'] = $val['title'];
            $temp['start_date'] = $start_date;
            $temp['end_date'] = $end_date;
            $temp['is_run'] = 0;
            $temp_pk = [];
            $temp_pk['pk_id'] = $val['pk_id'];
            $temp_pk['state'] = -2;
            array_push($pikuan_data, $temp_pk);
            array_push($save_data, $temp);
        }
        if (count($save_data)) {
            $pikuanRundb = new PikuanRundb();
            $pikuanRundb->saveAll($save_data);
            $pikuandb->saveAll($pikuan_data);
        }
        $this->layuiReturn([]);

    }

    // 匹款按钮
    public function titlePikuanBack()
    {
        $pikuandb = new Pikuandb();
        $pikuandb->param = $this->post['where_json'];
        $where = $pikuandb->where('state', -1)->select();
        halt($pikuandb->getLastSql());
        if (count($where) > 500) {
            $this->layuiReturn(500, 0, '同时匹款' . count($where) . '，超过500条，请先优化再匹款', 1);
        }
        //$where = $this->post['where'];
        $result = [];
        $pikuan_arr = [];
        $pikuan_save_arr = [];
        foreach ($where as $key => $val) {
            $pkxx = '';
            $save_data = [];
            switch ($this->post['times']) {
                case 1:
                    // 发票抬头组合匹款
                    $get_order = Db::name('order')->where('huikuandanwei', $val['title'])
                        //->fetchSql(true)
                        ->where('pay_state', 1)
                        ->whereNotIn('jun_order_state', [6, 7, 9])
                        ->whereNotIn('order_type', [5, 7])
                        ->where('order_money', '<=', $val['money'] * 100)
                        ->whereTime('create_time', 'between', [$this->post['start_time'], $this->post['end_time']])
                        ->order('order_money', 'desc')
                        ->field('out_order_no,order_money')
                        ->select();
                    $pkxx = $val['title'];
                    break;
                case 2:
                    // 地址匹款
                    $pikuan_arr = Db::name('pikuanxinxi')
                        ->where('fkdw', $val['title'])
                        ->where('address', '<>', '#N/A')
                        ->column('address');
                    $pikuan_arr = array_filter($pikuan_arr, function ($value) {
                        if ($value) {
                            return $value;
                        }
                    });
                    $pkxx = implode(',', $pikuan_arr);
                    if (count($pikuan_arr) == 0) {
                        $get_order = [];
                    } else {
                        $shopping_sql = '(select shopping_id from ys_shopping where CONCAT(province,city,area,street) IN ("' . implode('","', $pikuan_arr) . '"))';
                        $get_order = Db::name('order')
                            ->alias('order')
                            ->join($shopping_sql . ' as shopping', 'order.shopping_id = shopping.shopping_id')
                            ->where('order.pay_state', 1)
                            ->whereTime('order.create_time', 'between', [$this->post['start_time'], $this->post['end_time']])
                            //->fetchSql(true)
                            ->whereNotIn('order.jun_order_state', [6, 7, 9])
                            ->whereNotIn('order.order_type', [5, 7])
                            ->where('order.order_money', '<=', $val['money'] * 100)
                            ->order('order.order_money', 'desc')
                            ->field('order.out_order_no,order.order_money')
                            ->select();

                        /*print_r($get_order);
                        exit();*/
                    }
                    break;
                case 3:
                    // 手机号匹款 这里调用订单后表中的手机号，如果不对可以借鉴上面的地址匹款
                    $pikuan_arr = Db::name('pikuanxinxi')
                        ->where('fkdw', $val['title'])
                        ->where('phone', '<>', '#N/A')
                        ->column('phone');
                    $pikuan_arr = array_filter($pikuan_arr, function ($value) {
                        if ($value) {
                            return $value;
                        }
                    });
                    $pkxx = implode(',', $pikuan_arr);
                    if (count($pikuan_arr) == 0) {
                        $get_order = [];
                    } else {
                        $get_order = Db::name('order')
                            //->fetchSql(true)
                            ->where('pay_state', 1)
                            ->whereIn('phone', $pikuan_arr)
                            ->whereTime('create_time', 'between', [$this->post['start_time'], $this->post['end_time']])
                            ->whereNotIn('jun_order_state', [6, 7, 9])
                            ->whereNotIn('order_type', [5, 7])
                            ->where('order_money', '<=', $val['money'] * 100)
                            ->order('order_money', 'desc')
                            ->field('out_order_no,order_money')
                            ->select();
                        //halt($get_order);
                    }
                    break;
                case 4:
                    // 销项票匹款
                    $pikuan_arr = Db::name('pikuanxinxi')->where('fkdw', $val['title'])->column('xxp');
                    $pikuan_arr = array_filter($pikuan_arr, function ($value) {
                        if ($value) {
                            return $value;
                        }
                    });
                    $pkxx = implode(',', $pikuan_arr);
                    if (count($pikuan_arr) == 0) {
                        $get_order = [];
                    } else {
                        $invoice_sql = Db::name('invoice')
                            ->fetchSql(true)
                            ->whereIn('invoice_title', $pikuan_arr)
                            ->column('order_nos');
                        $get_order = Db::name('order')
                            ->alias('order')
                            //->fetchSql(true)
                            ->where('order.pay_state', 1)
                            ->whereTime('order.create_time', 'between', [$this->post['start_time'], $this->post['end_time']])
                            ->whereNotIn('order.jun_order_state', [6, 7, 9])
                            ->whereNotIn('order.order_type', [5, 7])
                            ->join('(' . $invoice_sql . ') as invoice', 'order.order_no = invoice.order_nos')
                            ->where('order.order_money', '<=', $val['money'] * 100)
                            ->order('order.order_money', 'desc')
                            ->field('order.out_order_no,order.order_money')
                            ->select();
                        /*print_r($get_order.';'.chr(13));
                        exit();*/
                    }
                    break;
            }
            /*print_r($get_order);
            exit();*/
            //print_r(count($get_order).'===');


            if (count($get_order) > 0 && !$get_order->isEmpty()) {
                $get_order = $get_order->toArray();
                // 运算次数超过1亿
                //print_r(pow(count($get_order), $this->post['order_level']));
                if (pow(count($get_order), $this->post['order_level']) > 100000000) {
                    $result[$val['return_code']] = '数据量过大';
                    $result['data'] = $get_order;
                } else {
                    $combinations = $this->getCombinations($get_order, $val['money'] * 100);
                    $result[$val['return_code']] = $this->uniqueArray($combinations);
                }

            } else {
                $result[$val['return_code']] = [];
            }
            if ($result[$val['return_code']] == '数据量过大') {
                $save_data['runs'] = 3;
                $result[$val['return_code']] = [];
            } else {
                if (count($result[$val['return_code']]) == 1) {
                    $save_data['runs'] = 1;
                } elseif (count($result[$val['return_code']]) == 0) {
                    $save_data['runs'] = 0;
                } else {
                    $save_data['runs'] = 2;
                }
            }
            $save_data['pk_id'] = $val['pk_id'];
            $save_data['times'] = $this->post['times'] + 1;
            $save_data['order_level'] = $this->post['order_level'] - 1;
            $save_data['order_no_group'] = $result[$val['return_code']];
            $save_data['default_group'] = $result[$val['return_code']][0] ?? [];
            $save_data['admin_id'] = MEMBER_ID;
            $save_data['pkxx'] = $pkxx;
            array_push($pikuan_save_arr, $save_data);
        }
        $pikuandb->saveAll($pikuan_save_arr);
        $this->layuiReturn($result);

    }

    // 匹配数据去重
    protected function uniqueArray($array)
    {
        $uniqueArray = array();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = $this->uniqueArray($value); // 递归处理子数组
            }

            if (!in_array($value, $uniqueArray)) {
                $uniqueArray[$key] = $value;
            }
        }

        return $uniqueArray;
    }


    // 匹配订单组合
    protected function getCombinations($orders, $money, $currentSum = 0, $currentOrder = [], $count = 0)
    {
        $result = [];
        $count++;
        // 检查当前累加金额是否大于等于100，如果是，则将当前组合添加到结果数组中
        if ($currentSum >= $money) {
            sort($currentOrder);
            $count = 0;
            $result[] = $currentOrder;
        } else {
            // 遍历订单数组
            foreach ($orders as $order) {
                if (in_array($order['out_order_no'], $currentOrder)) {
                    continue;
                }
                // 计算新的累加金额和新的订单组合
                $newSum = $currentSum + intval($order['order_money']);
                $newOrder = $currentOrder;
                $newOrder[] = $order['out_order_no'];

                // $count如果大于6根据数据量可能会崩溃
                if ($newSum <= $money && $count < $this->post['order_level']) {
                    $result = array_merge($result, $this->getCombinations($orders, $money, $newSum, $newOrder, $count));
                }
            }
        }

        return $result;
    }

    // 确认提交操作数据
    public function renkuanBack2()
    {
        $pikuandb = new Pikuandb();
        $save_all = [];
        $post = $this->post['post'];
        $orderdb = new Orderdb();
        foreach ($post as $key => $val) {
            $temp['return_code'] = $val['return_code'];
            $temp['pay_time'] = $val['pay_time'];
            $temp['title'] = $val['title'];
            $temp['money'] = $val['money'];
            $temp['order_nos'] = implode(',', $val['default_group']);
            $temp['supplier_id'] = Db::name('order')->where('out_order_no', $val['default_group'][0])->value('supplier_id');
            $temp['state'] = $val['state'];
            // 如果state ==1 要设置订单状态为已收款
            if ($val['state'] == 1) {
                foreach ($val['default_group'] as $out_order_no) {
                    // 直接更新
                    $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
                    //$get_order->save(['pay_state' => 2, 'pay_time' => strtotime($val['pay_time'])]);
                }
            }
            array_push($save_all, $temp);
        }
        $pikuandb->saveAll($save_all);
        $this->layuiReturn([], 1, '提交成功', 1);
    }

    // 单项认款
    public function renkuan()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->find($this->post['pk_id']);
        if ($get_pikuan) {
            $out_order_no_arr = [];
            if ($this->post['state'] == 1) {
                $default_group = [];
                if (!is_array($get_pikuan['default_group'])) {
                    $default_group[] = $get_pikuan['default_group'];
                } else {
                    $default_group = $get_pikuan['default_group'];
                }
                foreach ($default_group as $out_order_no) {
                    // 直接更新
                    //$get_order = $orderdb->where('out_order_no', $out_order_no)->find();
                    //$get_order->save(['pay_state' => 2, 'pay_time' => strtotime($get_pikuan['pay_time'])]);
                    array_push($out_order_no_arr, $out_order_no);
                }
                $log_text = '认款成功';
            } else {
                $default_group = $get_pikuan['default_group'];
                if (!is_array($get_pikuan['default_group'])) {
                    $default_group = explode(',', $default_group);
                }
                foreach ($default_group as $out_order_no) {
                    array_push($out_order_no_arr, $out_order_no);
                }
                $log_text = '认款待核实';
            }
            if (date('H') > 0) {
                $renkuanshijian = date('Y-m-d', strtotime('+1 day'));
            } else {
                $renkuanshijian = date('Y-m-d');
            }
            $get_pikuan->save(['state' => $this->post['state'], 'admin_id' => MEMBER_ID, 'renkuanshijian' => $renkuanshijian, 'order_nos' => implode(',', $out_order_no_arr)]);

            $log_data = [];
            $log_data['return_code'] = $get_pikuan['return_code'];
            $log_data['log_txt'] = $log_text;
            $log_data['param'] = json_encode($this->post);
            $log_data['log_date'] = date('Y-m-d H:i:s');
            $log_data['result'] = '';
            $log_data['result'] = '申请成功';
            $log_data['admin_id'] = MEMBER_ID;
            $pikuanLogdb = new PikuanLogdb();
            $pikuanLogdb->save($log_data);

        }
        $this->layuiReturn([], 1, '提交成功', 1);
    }

    // 多项认款
    public function renkuanmul()
    {
        $pikuanLogdb = new PikuanLogdb();
        $pikuandb = new Pikuandb();
        $orderdb = new Orderdb();
        $log_arr = [];
        foreach ($this->post['data'] as $pkid) {
            $get_pikuan = $pikuandb->find($pkid);
            if ($get_pikuan) {
                $out_order_no_arr = [];
                if (is_array($get_pikuan['default_group'])) {
                    foreach ($get_pikuan['default_group'] as $out_order_no) {
                        // 直接更新
                        $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
                        //$get_order->save(['pay_state' => 2, 'pay_time' => strtotime($get_pikuan['pay_time'])]);
                        array_push($out_order_no_arr, $out_order_no);
                    }
                } else {
                    $get_order = $orderdb->where('out_order_no', $get_pikuan['default_group'])->find();
                    //$get_order->save(['pay_state' => 2, 'pay_time' => strtotime($get_pikuan['pay_time'])]);
                    array_push($out_order_no_arr, $get_pikuan['default_group']);
                }
                if (date('H') > 0) {
                    $renkuanshijian = date('Y-m-d', strtotime('+1 day'));
                } else {
                    $renkuanshijian = date('Y-m-d');
                }
                $get_pikuan->save(['state' => $this->post['state'], 'admin_id' => MEMBER_ID, 'renkuanshijian' => $renkuanshijian, 'order_nos' => implode(',', $out_order_no_arr)]);

                $log_data = [];
                $log_data['return_code'] = $get_pikuan['return_code'];
                $log_data['log_txt'] = '多项认款';
                $log_data['param'] = json_encode($this->post);
                $log_data['log_date'] = date('Y-m-d H:i:s');
                $log_data['result'] = '';
                $log_data['result'] = '申请成功';
                $log_data['admin_id'] = MEMBER_ID;
                array_push($log_arr,$log_data);
            }
        }
        $pikuanLogdb->saveAll($log_arr);
        $this->layuiReturn([], 1, '提交成功', 1);
    }

    // 选择匹款订单分组
    public function updateSelect()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->find($this->post['pk_id']);
        if ($get_pikuan) {
            $get_pikuan->save(['default_group' => $this->post['default_group']]);
        }
        //$this->post['state'] = 1;
        //$this->renkuan();
        $this->layuiReturn([], 1, '提交成功', 1);
    }

    // 提交手动认款数据

    public function shoudong()
    {
        $pikuandb = new Pikuandb();
        $save_all = [];
        $post = $this->post['post'];
        foreach ($post as $key => $val) {
            $temp['return_code'] = $val['return_code'];
            $temp['pay_time'] = $val['pay_time'];
            $temp['title'] = $val['title'];
            $temp['money'] = $val['money'];
            $temp['order_nos'] = '';
            $temp['supplier_id'] = 0;
            $temp['state'] = 0;
            array_push($save_all, $temp);
        }
        $pikuandb->saveAll($save_all);
        $this->layuiReturn([], 1, '提交成功', 1);
    }

    // 匹款成功，认款
    public function renkuanBack()
    {
        // 校验要匹款的订单是否已支付
        $orderdb = new Orderdb();
        $chk_order = $orderdb->whereIn('out_order_no', $this->post['default_group'])->field('out_order_no,pay_state,supplier_id,order_id')->select();
        $err_order = [];
        $update_data = [];
        foreach ($chk_order as $key => $val) {
            if ($val['pay_state'] != 1) {
                array_push($err_order, $val['out_order_no']);
            }
            array_push($update_data, [
                'order_id' => $val['order_id'],
                //'pay_state' => 2,
                //'pay_time' => strtotime($this->post['pay_time'])
            ]);
        }
        // 校验不成功
        /*if (count($err_order) > 0) {
            $this->layuiReturn($err_order, 0, '校验错误', 0);
        }*/
        // 验证成功后
        $pikuandb = new Pikuandb();
        $pikuandb->save([
            'return_code' => $this->post['return_code'],
            'pay_time' => $this->post['pay_time'],
            'title' => $this->post['title'],
            'money' => $this->post['money'],
            'intro' => $this->post['intro'],
            'order_nos' => implode(',', $this->post['default_group']),
            'supplier_id' => $chk_order[0]['supplier_id'],
            'state' => 1
        ]);
        // 同步设置收款状态和收款时间
        $orderdb->saveAll($update_data);
        $this->layuiReturn([], 1, '认款成功', 1);
    }

    // 匹配成功，等待认款
    public function queren()
    {
        // 校验要匹款的订单是否已支付
        $orderdb = new Orderdb();
        $chk_order = $orderdb->whereIn('out_order_no', $this->post['default_group'])->field('out_order_no,pay_state,supplier_id,order_id')->select();
        $err_order = [];
        foreach ($chk_order as $key => $val) {
            if ($val['pay_state'] != 1) {
                array_push($err_order, $val['out_order_no']);
            }
        }
        // 校验不成功
        /*if (count($err_order) > 0) {
            $this->layuiReturn($err_order, 0, '校验错误', 0);
        }*/
        // 验证成功后
        $pikuandb = new Pikuandb();
        $pikuandb->save([
            'return_code' => $this->post['return_code'],
            'pay_time' => $this->post['pay_time'],
            'title' => $this->post['title'],
            'money' => $this->post['money'],
            'intro' => $this->post['intro'],
            'order_nos' => implode(',', $this->post['default_group']),
            'supplier_id' => $chk_order[0]['supplier_id'],
            'state' => 2
        ]);
        // 同步设置收款状态和收款时间
        $this->layuiReturn([], 1, '操作成功', 1);
    }

    // 查看匹配订单信息
    public function viewOrder()
    {
        $order_no_arr = [];
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->where('pk_id', $this->post['pk_id'])->find();
        if (!in_array($get_pikuan['state'], [1, 2])) {
            if(isset($this->post['order_no_group'])) {
                $order_no_group = $this->post['order_no_group'];
            } else {
                if(!isset($get_pikuan['order_no_group'][0])) {
                    $order_no_group = $get_pikuan['order_no_group'][0];
                }
            }
            if (is_array($order_no_group[0])) {
                foreach ($order_no_group as $key => $val) {
                    foreach ($val as $k => $v) {
                        array_push($order_no_arr, $v);
                    }
                }
            } else {
                for ($i = 0; $i < count($order_no_group); $i++) {
                    array_push($order_no_arr, $order_no_group[$i]);
                }
            }
        } else {
            $get_pikuan_order_no = Db::name('pikuan')->where('pk_id', $this->post['pk_id'])->value('order_nos');
            $order_no_arr = explode(',', $get_pikuan_order_no);
        }
        $get_detail = Db::name('order')->alias('order')
            //->fetchSql(true)
            ->join('member member', 'order.supplier_id=member.member_id', 'LEFT')
            ->join('shopping shopping', 'order.shopping_id=shopping.shopping_id', 'LEFT')
            ->join('invoice invoice', 'order.order_no = invoice.order_nos')
            ->field('
            order.out_order_no,order.order_no,order.order_money,order.supplier_id,order.yonghu_beizhu,order.jun_order_state,
            member.company_name,
            invoice.invoice_title huikuandanwei,
            shopping.province,shopping.city,shopping.area,shopping.street,shopping.contacts,shopping.phone
            ')
            ->whereIn('out_order_no', $order_no_arr)
            ->select()->toArray();
        foreach ($get_detail as $key => $val) {
            $get_detail[$key]['cart'] = Db::name('cart')->where('order_no', $val['order_no'])->field('goods_sku,product_firm fpmc')->select()->toArray();
        }

        $get_xinxi = [];
        if ($get_pikuan['title']) {
            $get_xinxi = Db::name('pikuanxinxi')->where('fkdw', $get_pikuan['title'])->select();
        }
        $get_pikuan_arr = $pikuandb->where('pk_id', $this->post['pk_id'])->field('order_no_group,default_group')->find();
        $get_pikuan_index = 0;
        if ($get_pikuan_arr) {
            foreach ($get_pikuan_arr['order_no_group'] as $key => $val) {
                if ($val == $get_pikuan_arr['default_group']) {
                    $get_pikuan_index = $key;
                }
            }
        }
        $this->layuiReturn($get_detail, $get_pikuan_index, $get_xinxi, in_array($get_pikuan['state'], [1, 2]) ? 1 : 0);
    }

    // 查看质疑订单

    public function viewZhiyiOrder()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = Db::name('pikuan')->where('pk_id', $this->post['pk_id'])->field('zhiyi_order,is_mul,mul_code')->find();
        $get_detail = Db::name('order')->alias('order')
            ->join('member member', 'order.supplier_id=member.member_id', 'LEFT')
            ->join('shopping shopping', 'order.shopping_id=shopping.shopping_id', 'LEFT')
            ->join('invoice invoice', 'order.order_no = invoice.order_nos')
            ->field('order.out_order_no,order.order_no,order.order_money,invoice.invoice_title huikuandanwei,order.supplier_id,order.yonghu_beizhu,order.jun_order_state,member.company_name,shopping.province,shopping.city,shopping.area,shopping.street,shopping.contacts,shopping.phone')
            ->whereIn('out_order_no', explode(',', $get_pikuan['zhiyi_order']))
            ->select()->toArray();

        foreach ($get_detail as $key => $val) {
            $get_detail[$key]['cart'] = Db::name('cart')->where('order_no', $val['order_no'])->field('goods_sku,product_firm fpmc')->select()->toArray();
            if (is_numeric($val['province'])) {
                $get_area_arr = $this->areaidToName($val['province'], $val['city'], $val['area']);
                $get_detail[$key]['province'] = $get_area_arr['province'];
                $get_detail[$key]['city'] = $get_area_arr['city'];
                $get_detail[$key]['area'] = $get_area_arr['area'];
            }
        }

        $pikuandb = new Pikuandb();
        $get_pikuan_title = $pikuandb->where('pk_id', $this->post['pk_id'])->value('title');
        $get_xinxi = [];
        if ($get_pikuan_title) {
            $get_xinxi = Db::name('pikuanxinxi')->where('fkdw', $get_pikuan_title)->select();
        }
        $this->layuiReturn(array('data' => $get_detail, 'pikuan' => $get_pikuan), 1, $get_xinxi, 1);
    }

    // 地区转换
    protected function areaidToName($p, $c, $a)
    {
        $return_arr = array();
        $json_str = file_get_contents('./static/js/jqcity/allcity.js');
        $json_str = str_replace('callback(', '', $json_str);
        $json_str = str_replace(');', '', $json_str);
        $json_arr = json_decode($json_str, true);
        for ($i = 0; $i < count($json_arr['province']); $i++) {
            if ($p == $json_arr['province'][$i]['id']) {
                $return_arr['province'] = $json_arr['province'][$i]['name'];
                break;
            }
        }
        for ($i = 0; $i < count($json_arr['city'][$p]); $i++) {
            if ($c == $json_arr['city'][$p][$i]['id']) {
                $return_arr['city'] = $json_arr['city'][$p][$i]['name'];
                break;
            }
        }
        for ($i = 0; $i < count($json_arr['district'][$c]); $i++) {
            if ($a == $json_arr['district'][$c][$i]['id']) {
                $return_arr['area'] = $json_arr['district'][$c][$i]['name'];
                break;
            }
        }
        return $return_arr;
    }

    // 完成匹款单
    public function over()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->find($this->post['pk_id']);
        // 校验一个订单多个回款单号
        if ($get_pikuan['is_mul'] == 1) {
            $pikuan_list = $pikuandb->whereIn('return_code', explode(',', $get_pikuan['mul_code']))->select();
            $save_pikuan = [];
            foreach ($pikuan_list as $k => $v) {
                $temp = [];
                $temp['pk_id'] = $v['pk_id'];
                $temp['state'] = 2;
                array_push($save_pikuan, $temp);
            }
            $pikuandb->saveAll($save_pikuan);
        } else {
            $get_pikuan->save(['state' => 2]);
        }
        // 校验完成
        // 日志
        $pikuanLogdb = new PikuanLogdb();
        $log_data = [];
        $log_data['return_code'] = $get_pikuan['return_code'];
        $log_data['log_txt'] = '完成匹款';
        $log_data['param'] = json_encode($this->post);
        $log_data['result'] = '操作成功';
        $log_data['log_date'] = date('Y-m-d H:i:s');
        $log_data['admin_id'] = MEMBER_ID;
        $pikuanLogdb->save($log_data);
        // 日志结束
        $this->layuiReturn('操作成功');
    }

    /**
     * Title("校验质疑订单是否已认款")
     */
    public function chkOrder()
    {
        $get_title = Db::name('pikuan')
            //->fetchSql(true)
            ->where('order_nos', $this->post['order_nos'])
            //->where('order_nos','20211015120000189001')
            ->where('state', 1)->where('zhiyi_state', 1)->find();
        if ($get_title) {
            $this->layuiReturn($get_title['title'], 1, 'success', 1);
        } else {
            $this->layuiReturn('', 1, 'error', 0);
        }
    }

    // 确定通过质疑
    public function pass()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->find($this->post['pk_id']);
        // 校验一个订单多个回款单号
        if ($get_pikuan['is_mul'] == 1) {
            $pikuan_list = $pikuandb->whereIn('return_code', explode(',', $get_pikuan['mul_code']))->select();
            $save_pikuan = [];
            foreach ($pikuan_list as $k => $v) {
                $temp = [];
                $temp['pk_id'] = $v['pk_id'];
                $temp['state'] = 1;
                $temp['zhiyi_state'] = 1;
                $temp['order_nos'] = $v['zhiyi_order'];
                $temp['renkuanshijian'] = date('Y-m-d', strtotime('+1 day'));
                array_push($save_pikuan, $temp);
            }
            $pikuandb->saveAll($save_pikuan);
        } else {
            $get_pikuan->save(['state' => 1, 'zhiyi_state' => 1, 'order_nos' => $get_pikuan['zhiyi_order'], 'renkuanshijian' => date('Y-m-d', strtotime('+1 day'))]);
        }
        // 校验结束
        // 如果待确认，直接修改订单状态，否则回滚订单支付状态
        $orderdb = new Orderdb();
        if ($get_pikuan['state'] == 1) {
            // 回滚
            $back_order = Db::name('order')->whereIn('out_order_no', explode(',', $get_pikuan['order_nos']))->select();
            $back_data = [];
            foreach ($back_order as $order) {
                $temp['pay_state'] = 1;
                $temp['pay_time'] = null;
                $temp['order_id'] = $order['order_id'];
                array_push($back_data, $temp);
            }
            $orderdb->saveAll($back_data);

        }
        // 添加新数据
        $update_order = Db::name('order')->whereIn('out_order_no', explode(',', $get_pikuan['zhiyi_order']))->select();
        $update_data = [];
        foreach ($update_order as $order) {
            //$temp['pay_state'] = 2;
            //$temp['pay_time'] = strtotime($get_pikuan['pay_time']);
            if (date('H') > 0) {
                $temp['renkuanshijian'] = date('Y-m-d', strtotime('+1 day'));
            } else {
                $temp['renkuanshijian'] = date('Y-m-d');
            }
            $temp['order_id'] = $order['order_id'];
            array_push($update_data, $temp);
        }
        $orderdb->saveAll($update_data);
        // 日志
        $pikuanLogdb = new PikuanLogdb();
        $log_data = [];
        $log_data['return_code'] = $get_pikuan['return_code'];
        $log_data['log_txt'] = '审核通过质疑申请';
        $log_data['param'] = json_encode($this->post);
        $log_data['result'] = '操作成功';
        $log_data['log_date'] = date('Y-m-d H:i:s');
        $log_data['admin_id'] = MEMBER_ID;
        $pikuanLogdb->save($log_data);
        // 日志结束
        $this->layuiReturn('操作成功', 1, '', 1);
    }

    /**
     * Title("批量确认通过质疑")
     */
    public function passmul()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->whereIn('pk_id', $this->post['data'])->select();
        $log_save = [];
        foreach ($get_pikuan as $key => $val) {
            // 校验一个订单多个回款单号
            if ($val['is_mul'] == 1) {
                $pikuan_list = $pikuandb->whereIn('return_code', explode(',', $val['mul_code']))->select();
                $save_pikuan = [];
                foreach ($pikuan_list as $k => $v) {
                    $temp = [];
                    $temp['pk_id'] = $v['pk_id'];
                    $temp['state'] = 1;
                    $temp['zhiyi_state'] = 1;
                    $temp['order_nos'] = $v['zhiyi_order'];
                    $temp['renkuanshijian'] = date('Y-m-d', strtotime('+1 day'));
                    array_push($save_pikuan, $temp);
                }
                $pikuandb->saveAll($save_pikuan);
            } else {
                $val->save(['state' => 1, 'zhiyi_state' => 1, 'order_nos' => $val['zhiyi_order'], 'renkuanshijian' => date('Y-m-d', strtotime('+1 day'))]);
            }
            // 校验结束
            // 如果待确认，直接修改订单状态，否则回滚订单支付状态
            $orderdb = new Orderdb();
            if ($val['state'] == 1) {
                // 回滚
                $back_order = Db::name('order')->whereIn('out_order_no', explode(',', $val['order_nos']))->select();
                $back_data = [];
                foreach ($back_order as $order) {
                    $temp['pay_state'] = 1;
                    $temp['pay_time'] = null;
                    $temp['order_id'] = $order['order_id'];
                    array_push($back_data, $temp);
                }
                $orderdb->saveAll($back_data);
            }
            // 添加新数据
            $update_order = Db::name('order')->whereIn('out_order_no', explode(',', $val['zhiyi_order']))->select();
            $update_data = [];
            foreach ($update_order as $order) {
                if (date('H') > 0) {
                    $temp['renkuanshijian'] = date('Y-m-d', strtotime('+1 day'));
                } else {
                    $temp['renkuanshijian'] = date('Y-m-d');
                }
                $temp['order_id'] = $order['order_id'];
                array_push($update_data, $temp);
            }
            $orderdb->saveAll($update_data);

            // 日志
            $log_data = [];
            $log_data['return_code'] = $val['return_code'];
            $log_data['log_txt'] = '批量审核通过质疑申请';
            $log_data['param'] = json_encode(array('pk_id' => $val['pk_id']));
            $log_data['result'] = '操作成功';
            $log_data['log_date'] = date('Y-m-d H:i:s');
            $log_data['admin_id'] = MEMBER_ID;
            array_push($log_save, $log_data);
            // 日志结束

        }
        $pikuanLogdb = new PikuanLogdb();
        $pikuanLogdb->saveAll($log_save);

        $this->layuiReturn('操作成功', 1, '', 1);
    }

    // 驳回质疑
    public function reject()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->find($this->post['pk_id']);
        // 校验一个订单多个回款单号
        if ($get_pikuan['is_mul'] == 1) {
            $pikuan_list = $pikuandb->whereIn('return_code', explode(',', $get_pikuan['mul_code']))->select();
            $save_pikuan = [];
            foreach ($pikuan_list as $k => $v) {
                $temp = [];
                $temp['pk_id'] = $v['pk_id'];
                $temp['zhiyi_state'] = 2;
                $temp['reject_reason'] = $this->post['reject_reason'];
                $temp['is_mul'] = 0;
                $temp['mul_code'] = '';
                array_push($save_pikuan, $temp);
            }
            $pikuandb->saveAll($save_pikuan);
        } else {
            $get_pikuan->save(['zhiyi_state' => 2, 'reject_reason' => $this->post['reject_reason']]);
        }
        // 校验结束

        // 日志
        $pikuanLogdb = new PikuanLogdb();
        $log_data = [];
        $log_data['return_code'] = $get_pikuan['return_code'];
        $log_data['log_txt'] = '驳回质疑申请';
        $log_data['param'] = json_encode($this->post);
        $log_data['result'] = '操作成功';
        $log_data['log_date'] = date('Y-m-d H:i:s');
        $log_data['admin_id'] = MEMBER_ID;
        $pikuanLogdb->save($log_data);
        // 日志结束
        $this->layuiReturn('操作成功');
    }

    /**
     * Title("批量驳回")
     */
    public function rejectmul()
    {
        $pikuandb = new Pikuandb();
        $get_pikuan = $pikuandb->whereIn('pk_id', $this->post['data'])->select();
        $log_save = [];
        $save_pikuan = [];
        foreach ($get_pikuan as $key => $val) {
            // 校验一个订单多个回款单号
            if ($val['is_mul'] == 1) {
                $pikuan_list = $pikuandb->whereIn('return_code', explode(',', $val['mul_code']))->select();
                $save_pikuan = [];
                foreach ($pikuan_list as $k => $v) {
                    $temp = [];
                    $temp['pk_id'] = $v['pk_id'];
                    $temp['zhiyi_state'] = 2;
                    $temp['reject_reason'] = $this->post['reject_reason'];
                    $temp['is_mul'] = 0;
                    $temp['mul_code'] = '';
                    array_push($save_pikuan, $temp);
                }
                $pikuandb->saveAll($save_pikuan);
            } else {
                array_push($save_pikuan, ['pk_id' => $val['pk_id'], 'zhiyi_state' => 2, 'reject_reason' => $this->post['reject_reason']]);
            }
            // 校验结束

            // 日志
            $log_data = [];
            $log_data['return_code'] = $val['return_code'];
            $log_data['log_txt'] = '批量驳回质疑申请';
            $log_data['param'] = json_encode(array('pk_id' => $val['pk_id'], 'reject_reason' => $this->post['reject_reason']));
            $log_data['result'] = '操作成功';
            $log_data['log_date'] = date('Y-m-d H:i:s');
            $log_data['admin_id'] = MEMBER_ID;
            array_push($log_save, $log_data);
        }
        $pikuandb->saveAll($save_pikuan);
        $pikuanLogdb = new PikuanLogdb();
        $pikuanLogdb->saveAll($log_save);
        $this->layuiReturn('操作成功');
    }

    // 申请质疑订单
    public function zhiyi()
    {
        $mul_code = explode(',', $this->post['return_code_mul']);
        $pikuandb = new Pikuandb();
        $orderdb = new Orderdb();
        $pikuanLogdb = new PikuanLogdb();
        if (count($mul_code) > 1) {
            // 一个订单对应多个回款编号
            $get_pikuan = $pikuandb
                ->whereIn('return_code', $mul_code)
                ->where('is_delete', 0)
                ->where('state', '<>', 2)
                ->select();
            if (count($get_pikuan) != count($mul_code)) {
                $this->layuiReturn('回款单号中存在不可用单号', 0, '回款单号中存在不可用单号', 0);
            }
            $all_money = 0;
            $pikuan_data = [];
            $log_arr = [];
            $zhiyiren = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
            foreach ($get_pikuan as $key => $val) {
                $all_money += $val['money'];
                $temp = [];
                $temp['pk_id'] = $val['pk_id'];
                $temp['is_mul'] = 1;
                $temp['mul_code'] = $this->post['return_code_mul'];
                $temp['zhiyi_order'] = $this->post['zhiyi_order'];
                $temp['zhiyi_state'] = 0;
                $temp['zhiyiren'] = $zhiyiren;
                $temp['dianqiantai'] = $this->post['dianqiantai'];
                array_push($pikuan_data, $temp);
                $log_data = [];
                $log_data['return_code'] = $val['return_code'];
                $log_data['log_txt'] = '订单对应多个回款单号申请匹款';
                $log_data['param'] = json_encode($this->post);
                $log_data['log_date'] = date('Y-m-d H:i:s');
                $log_data['result'] = '';
                $log_data['result'] = '申请成功';
                $log_data['admin_id'] = MEMBER_ID;
                array_push($log_arr, $log_data);
            }
            $get_order_money = $orderdb->where('out_order_no', $this->post['zhiyi_order'])->value('order_money');
            if (intval($all_money * 100) != intval($get_order_money)) {
                $this->layuiReturn('质疑订单金额不正确', 0, '质疑订单金额不正确', 0);
            }
            $pikuandb->saveAll($pikuan_data);
            $pikuanLogdb->saveAll($log_arr);
            $this->layuiReturn('申请成功', 1, '申请成功', 1);
        } else {
            $get_pikuan = $pikuandb->find($this->post['pk_id']);
            $get_count_order_money = $orderdb->whereIn('out_order_no', $this->post['zhiyi_order'])->sum('order_money');
            if ($get_count_order_money / 100 != $get_pikuan['money']) {
                $this->layuiReturn('质疑订单金额不正确', 0, '质疑订单金额不正确', 0);
            } else {
                $zhiyiren = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
                $get_pikuan->save(['zhiyi_order' => $this->post['zhiyi_order'], 'zhiyi_state' => 0, 'zhiyiren' => $zhiyiren, 'dianqiantai' => $this->post['dianqiantai'], 'is_mul' => 0, 'mul_code' => '']);
                // 日志
                $log_data = [];
                $log_data['return_code'] = $get_pikuan['return_code'];
                $log_data['log_txt'] = '申请质疑';
                $log_data['param'] = json_encode($this->post);
                $log_data['log_date'] = date('Y-m-d H:i:s');
                $log_data['result'] = '';
                $log_data['result'] = '申请成功';
                $log_data['admin_id'] = MEMBER_ID;
                $pikuanLogdb->save($log_data);
                $this->layuiReturn('申请成功', 1, '申请成功', 1);
            }
        }
    }
}